var App = Em.Application.create({
  ready : function() {
    App.initialize();
  }
});

App.DAO = Em.Object.create({
  getJSON : function(url, func) {
    var jqxhr = $.getJSON(url, func);
    jqxhr.error(function(jqXHR, textStatus, errorThrown) {
      console.debug("error " + textStatus);
      console.debug("incoming Text " + jqXHR.responseText);
    });
  },
  ajax : function(obj) {
    var jqxhr = $.ajax(obj);
    jqxhr.error(function(jqXHR, textStatus, errorThrown) {
      console.debug("error " + textStatus);
      console.debug("incoming Text " + jqXHR.responseText);
    });
  },
  findAll: function (kind, content) {
    this.getJSON('api/'+kind+'/findAll', function(data) {
      $.each(data, function(index, value) {
        content.pushObject(value);
      });
    });
  },
  create : function (kind, entity, doneCallback) {
    this.ajax({
      url: 'api/'+kind+'/create',
      type: "POST",
      dataType: 'json',
      data: entity,
      success: function(returnedEntity) {
        doneCallback(returnedEntity);
      }
    });
  }
});

App.Select = Em.Select.extend({});

App.UserView = Ember.View.extend({
      classNames : [ 'user-view' ],
      // template: Ember.Handlebars.compile("<a>user</a>")
      template : Ember.Handlebars
          .compile("<div class=\"btn-group\">"
              + "<a class=\"btn btn-inverse\" href=\"#\"><i class=\"icon-user icon-white\"></i> Avital Nahon</a>"
              + "<a class=\"btn btn-inverse dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\"><span class=\"caret\"></span></a>"
              + "<ul class=\"dropdown-menu\">"
              + "<li><a href=\"#\" {{action \"settings\" on=\"click\"}}><i></i>Settings</a></li>"
              + "<li><a href=\"#\" {{action \"logout\" on=\"click\"}}><i></i>Logout</a></li>"
              + "</ul>" + "</div>")
    });

//---------- Application --------------


App.ApplicationView = Ember.View.extend({  templateName : 'application' });

App.Router = Ember.Router.extend({
  enableLogging : true,
  root : Ember.Route.extend({
    index: Ember.Route.extend({
      route: '/',
      do1 : function(router, event) { event.context.do1(); },
      do2 : function(router, event) { event.context.do2(); }
    })
  })
});

App.FieldView = Em.View
    .extend({
      classNames : [ 'control-group' ],
      tagName : 'div',
      type : 'text',
      label : null,
      value : null,
      size : '30',
      required : null,
      requiredAttribute : (function() {
        if (this.get('required') === 'true') {
          return '';
        } else {
          return null;
        }
      }).property('required'),
      // childViews : 'labelView dataView'.w(),
      labelView : Em.View.extend({
        tagName : 'label',
        classNames : [ 'control-label' ],
        attributeBindings : [ 'for' ],
        forBinding : 'parentView.dataView.elementId',
        textBinding : 'parentView.label',
        requiredBinding : 'parentView.required',
        defaultTemplate : Em.Handlebars.compile('{{view.text}}')
      }),
      dataView : Em.TextField.extend({
        attributeBindings : 'type value size placeholder required'.w(),
        typeBinding : 'parentView.type',
        sizeBinding : 'parentView.size',
        valueBinding : 'parentView.value',
        requiredBinding : 'parentView.requiredAttribute'
      }),
      defaultTemplate : Ember.Handlebars
          .compile('{{view view.labelView}}<div class=\"controls\">{{view view.dataView}}{{#if view.required}} <i class=\"icon-hand-left\"></i>   {{/if}}</div>')
    });


App.TextField = App.FieldView.extend();

App.TextArea = App.FieldView.extend({
  dataView : Em.TextArea.extend()
});

App.EmailField = App.FieldView.extend({
  type : 'email'
});

App.PasswordField = App.FieldView.extend({
  type : 'password'
});

App.DateField = App.FieldView.extend({
  dataView : Em.TextField.extend({
    attributeBindings : 'type value size placeholder required'.w(),
    typeBinding : 'parentView.type',
    sizeBinding : 'parentView.size',
    valueBinding : 'parentView.value',
    requiredBinding : 'parentView.requiredAttribute',
    didInsertElement : function() {
      this.$().datepicker();
    }
  })
});

App.NumberTextField = Ember.TextField.extend({
  keyPress : function(event) {
    var charCode = event.which; // charCode will contain the code of the
                                // character inputted
    // console.log(charCode);
    // Allow: backspace, delete, tab, escape, and enter and dot
    if (charCode == 46 || charCode == 8 || charCode == 9 || charCode == 27
        || charCode == 13 ||
        // Allow: Ctrl+A
        (charCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
        (charCode >= 35 && charCode <= 39)) {
      // let it happen, don't do anything
    } else {
      if (event.shiftKey || (charCode < 48 || charCode > 57)) {
        event.preventDefault();
      }
      // var theChar = String.fromCharCode(charCode);
    }
  }
});

App.NumberField = App.FieldView.extend({
  dataView : App.NumberTextField
      .extend({
        type : 'number',
        attributeBindings : 'type value size placeholder min max step required'
            .w(),
        minBinding : 'parentView.min',
        maxBinding : 'parentView.max',
        sizeBinding : 'parentView.size',
        valueBinding : 'parentView.value',
        requiredBinding : 'parentView.requiredAttribute'
      })
});



App.TagField = Ember.TextField.extend({
  attributeBindings : ['value'],
  classNames: ['input-small']
});

App.TagsField = Ember.View.extend({
    tagName: "div",
    attributeBindings: ['value'],
    value: null,
    defaultTemplate : Ember.Handlebars.compile(
        '<div class="row">'+
        '{{#each item in tags}}'+
        '{{view App.TagField valueBinding="item"}} '+
        '{{/each}}'+
        '</div>'
        )
  });

App.PickerController = Ember.Object.extend({
  map : {}, // maps ids to objects
  url : null, // the REST url used to load the data
  selectedObject : null,
  selectedId : function() { 
    if (this.selectedObject != null) {
      return this.selectedObject.id;
    }
    return null;
  }.property('selectedObject'),
  selectedLabel : function() {
    if (this.selectedObject != null) {
      return this.selectedObject.symbol;
    }
    return null;
  }.property('selectedObject'),
  loaded : null,
  load : function(donefunc) {
    if (!this.loaded) {
      this.loaded = true;
      var me = this;
      App.DAO.getJSON('api/'+this.url, function(data) {
        var index = 0;
        $.each(data, function(index, value) {
          console.log('adding to map : ' + JSON.stringify(value));
          me.map[value.id] = value;
          if (index == 0) {
            me.set('selectedObject', value);
          }
          index++;
        });
        donefunc();
      });
    } else {
      donefunc();
    }
  },
  property : null,
  properties: [],
  source : function (typeahead, query) {
    var me = this;
    me.load(function() {
      $.each(me.map, function(key, value) {
//        console.log('process key='+key);
        typeahead.process(value);
      })
    });
  }
});

App.symbolController = App.PickerController.create({
  url : "symbol/pickerFindAll",
  property : 'id',
  properties: ['id','instrument', 'currency']
});


App.ApplicationController = Ember.Controller.extend({
  ctags: ['t1','t2','t3','t4'],
  
  c : App.symbolController,
  
  do1 : function() {
    this.set('ctags',['a','b','c']);
  },
  
  do2 : function() {
    this.c.load();
  },
  
  sym1 : null,
  sym2 : null,
  sym3 : null
  
});




App.TypeaheadField = App.FieldView.extend({
  controller: null,
  dataView : Em.TextField.extend({
    classNames : ['typeahead'],
    attributeBindings : 'type value size placeholder required'.w(),
    typeBinding : 'parentView.type',
    sizeBinding : 'parentView.size',
    valueBinding : 'parentView.value',
    requiredBinding : 'parentView.requiredAttribute',
    urlBinding: 'parentView.url',
    propertyBinding : 'parentView.property',
    propertiesBinding: 'parentView.properties',
    controllerBinding: 'parentView.controller',
    didInsertElement : function() {
      var me = this;
      var controller = me.get('controller');
      this.$().typeahead({
        strings : false,
        property : controller.property,
        properties: controller.properties,
        source : function (typeahead, query) {
          controller.source(typeahead, query);
        },
        menu: '<table class="table table-condensed typeahead dropdown-menu" style="width:400px">'+
        '<tbody></tbody></table>',
        item: '<tr> <td><a id="0"></a></td> <td><a id="1"></a></td> <td><a id="2"></a></td> </tr>',
        items : 10
      });
    }
  })
});

App.TypeaheadField.reopen({
  valueChanged: function() {
    console.log("typeahead value changed to /" + this.get('value') + "/");
  }.observes('value')
});

App.SymbolField = App.TypeaheadField.extend({
  controller: App.symbolController
});
